package com.opennews.openplatform.myspringbootmvccore.security;

import com.opennews.openplatform.myspringbootcore.common.constant.HttpHeader;
import com.opennews.openplatform.myspringbootcore.security.AuthRequestValidator;
import com.opennews.openplatform.myspringbootcore.security.MyClaims;
import com.opennews.openplatform.myspringbootcore.security.ParsedToken;
import jakarta.servlet.http.HttpServletRequest;

public class RequestIdentityExtractor {
    protected AuthRequestValidator authRequestValidator;
    protected HttpServletRequest request;

    public RequestIdentityExtractor(AuthRequestValidator authRequestValidator, HttpServletRequest request) {
        this.authRequestValidator = authRequestValidator;
        this.request = request;
    }

    /**
     * Gets claims from token in header.
     */
    public ParsedToken getToken() {
        // Gets authorization from request header.
        // The string should be like below example:
        // Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDU3ODIxNzUsImlhdCI6MTYwNTc3ODU3NSwiaWQiOiJ1c2VyLWlkIiwidXNlcm5hbWUiOiJIdWkiLCJyb2xlcyI6WyJBZG1pbiJdfQ.tKdhYNyeqOS_ITIV_F0sKT6N-NBFjxMkPyXAkzT43WQ
        String header = request.getHeader(HttpHeader.HTTP_HEADER_AUTHORIZATION);
        String authorizationHeader = header != null ? header.trim() : null;

        // Validates token string to see if it is a valid access token, and it does not expire yet.
        return authRequestValidator.checkAuthorizationHeader(authorizationHeader);
    }

    /**
     * Gets claims from token.
     *
     * @return
     */
    public MyClaims getClaims() {
        return getToken().claims;
    }
}
